package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.minecraft.component.DataComponentTypes;
import net.minecraft.component.type.ProfileComponent;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.Map;

public record BeheadingEnchantmentEffect(EnchantmentLevelBasedValue dropChance) implements EnchantmentEntityEffect {
    public static final MapCodec<BeheadingEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("drop_chance").forGetter(BeheadingEnchantmentEffect::dropChance)
            ).apply(instance, BeheadingEnchantmentEffect::new)
    );

    // 基础概率和每级增加的概率（百分比）
    private static final int BASE_DROP_CHANCE = 5; // 5%基础概率
    private static final int CHANCE_PER_LEVEL = 3; // 每级增加3%

    // 生物类型到头颅物品的映射
    private static final Map<EntityType<?>, ItemStack> HEAD_MAPPINGS = new HashMap<>();

    static {
        // 初始化原版生物头颅映射
        HEAD_MAPPINGS.put(EntityType.CREEPER, new ItemStack(Items.CREEPER_HEAD));
        HEAD_MAPPINGS.put(EntityType.ZOMBIE, new ItemStack(Items.ZOMBIE_HEAD));
        HEAD_MAPPINGS.put(EntityType.SKELETON, new ItemStack(Items.SKELETON_SKULL));
        HEAD_MAPPINGS.put(EntityType.WITHER_SKELETON, new ItemStack(Items.WITHER_SKELETON_SKULL));
        HEAD_MAPPINGS.put(EntityType.ENDER_DRAGON, new ItemStack(Items.DRAGON_HEAD));

        // 特殊处理：凋零掉落多个头颅
        // 这个在代码中单独处理
    }

    public static void initialize() {
        ServerLivingEntityEvents.AFTER_DEATH.register((entity, damageSource) -> {
            if (!(damageSource.getAttacker() instanceof PlayerEntity attacker)) {
                return;
            }

            // 检查主手和副手武器的斩首附魔
            ItemStack mainHandWeapon = attacker.getMainHandStack();
            ItemStack offHandWeapon = attacker.getOffHandStack();
            
            int maxLevel = 0;
            
            // 检查主手武器
            if (!mainHandWeapon.isEmpty()) {
                maxLevel = Math.max(maxLevel, getBeheadingLevel(mainHandWeapon));
            }
            
            // 检查副手武器
            if (!offHandWeapon.isEmpty()) {
                maxLevel = Math.max(maxLevel, getBeheadingLevel(offHandWeapon));
            }

            if (maxLevel <= 0) {
                return;
            }

            // 计算掉落概率
            int dropChance = BASE_DROP_CHANCE + (maxLevel - 1) * CHANCE_PER_LEVEL;
            World world = attacker.getWorld();

            if (world.getRandom().nextInt(100) >= dropChance) {
                return; // 概率检查失败
            }

            BlockPos pos = entity.getBlockPos();
            ItemStack headToDrop = getHeadForEntity(entity, maxLevel, attacker);

            if (!headToDrop.isEmpty()) {
                dropItemStack(world, pos, headToDrop);

                // 生成斩首特效（可选）
                if (world instanceof ServerWorld serverWorld) {
                    serverWorld.spawnParticles(
                            net.minecraft.particle.ParticleTypes.SWEEP_ATTACK,
                            entity.getX(), entity.getY() + entity.getHeight() * 0.8, entity.getZ(),
                            3, 0.5, 0.2, 0.5, 0.05
                    );
                }
            }
        });
    }
    
    // 新增方法：获取物品上的斩首附魔等级
    private static int getBeheadingLevel(ItemStack weapon) {
        var enchantments = EnchantmentHelper.getEnchantments(weapon);
        int level = 0;

        for (var entry : enchantments.getEnchantments()) {
            if (entry.getKey().isPresent()) {
                String enchantmentId = entry.getKey().get().getValue().toString();
                if (enchantmentId.equals("lucifer_treasure:beheading")) {
                    level = Math.max(level, enchantments.getLevel(entry));
                }
            }
        }
        
        return level;
    }

    private static ItemStack getHeadForEntity(net.minecraft.entity.LivingEntity entity, int enchantLevel, PlayerEntity killer) {
        EntityType<?> entityType = entity.getType();

        // 特殊处理：玩家头颅
        if (entity instanceof PlayerEntity player) {
            return createPlayerHead(player);
        }

        // 特殊处理：凋零掉落多个头颅
        if (entityType == EntityType.WITHER) {
            ItemStack witherSkulls = new ItemStack(Items.WITHER_SKELETON_SKULL);
            witherSkulls.setCount(Math.min(enchantLevel, 3)); // 最多3个
            return witherSkulls;
        }

        // 查找预定义的头颅映射
        if (HEAD_MAPPINGS.containsKey(entityType)) {
            return HEAD_MAPPINGS.get(entityType).copy();
        }

        // 如果没有预定义映射，不掉落头颅
        return ItemStack.EMPTY;
    }

    private static ItemStack createPlayerHead(PlayerEntity player) {
        ItemStack playerHead = new ItemStack(Items.PLAYER_HEAD);

        // 设置玩家头颅的皮肤信息
        ProfileComponent profile = new ProfileComponent(player.getGameProfile());
        playerHead.set(DataComponentTypes.PROFILE, profile);

        return playerHead;
    }

    private static void dropItemStack(World world, BlockPos pos, ItemStack stack) {
        if (world instanceof ServerWorld serverWorld) {
            ItemEntity itemEntity = new ItemEntity(
                    serverWorld,
                    pos.getX() + 0.5,
                    pos.getY() + 0.5,
                    pos.getZ() + 0.5,
                    stack
            );

            // 设置随机的掉落运动
            itemEntity.setVelocity(
                    (world.getRandom().nextFloat() - 0.5F) * 0.1F,
                    world.getRandom().nextFloat() * 0.2F,
                    (world.getRandom().nextFloat() - 0.5F) * 0.1F
            );

            serverWorld.spawnEntity(itemEntity);
        }
    }

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        // 主要逻辑在事件监听器中处理
        // 这个方法在post_attack事件中可能被调用，但斩首逻辑需要在死亡时处理
    }

    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 